package cn.com.jdyun.service.impl;

import cn.com.jdyun.dto.BdexResult;
import cn.com.jdyun.exception.BdexGatewayException;
import cn.com.jdyun.mapper.MessageMapper;
import cn.com.jdyun.mapper.MessageUserMapper;
import cn.com.jdyun.pojo.Message;
import cn.com.jdyun.pojo.MessageUser;
import cn.com.jdyun.pojo.User;
import cn.com.jdyun.service.MessageService;
import cn.com.jdyun.service.UserService;
import cn.com.jdyun.util.RedisUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author yzping
 * @date Created in 上午 10:36 2018/8/25 0025
 */
@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private UserService userService;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private MessageUserMapper messageUserMapper;
    @Autowired
    RedisUtil redisUtil;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertCommonMessage(String userId, String title, String messageInfo,String status) throws BdexGatewayException {
        Date cur = new Date();
        //Message实体类参数的设置
        Message message = new Message();
        message.setMessageType(Byte.valueOf("0"));
        message.setFlag(Byte.valueOf("0"));
        message.setStatus(new Byte(status));
        message.setCreateTime(cur);
        message.setUpdateTime(cur);
        //根据用户id查询用户昵称
        String nickName = userService.getById(userId).getNickName();
        if (StringUtils.isEmpty(nickName)) {
            throw new BdexGatewayException("用户昵称不能为空!");
        }
        message.setPublisher(nickName);
        if (title.length() > 100) {
            throw new BdexGatewayException("主题内容过长,请确认!");
        }
        message.setTitle(title);
//        if (messageInfo.length() > 255) {
//            throw new BdexGatewayException("发布的内容过长，请确认!");
//        }
        message.setMessage(messageInfo);

        List<Message> messagesList = new ArrayList<>();

        //存入缓存
        String messageRelease = redisUtil.get("MessageInfo");
        if (StringUtils.isEmpty(messageRelease)) {
            messagesList.add(message);
            String messageInfos = JSONObject.toJSONString(messagesList);
            redisUtil.set("MessageInfo", messageInfos);
        } else {
            messagesList = JSONArray.parseArray(messageRelease).toJavaList(Message.class);
            messagesList.add(message);
            redisUtil.set("MessageInfo", JSONObject.toJSONString(messagesList));
        }

        //插入一条消息记录
        messageMapper.insert(message);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateCommonMessage(Integer id, String title, String messageInfo) throws BdexGatewayException {
        Message message = messageMapper.selectByPrimaryKey(id);
        if (!message.getFlag().equals(Byte.valueOf("0"))) {
            throw new BdexGatewayException("该消息已发布，不能修改,请确认!");
        }
        Date cur = new Date();
        if (title.length() > 100) {
            throw new BdexGatewayException("主题内容过长,请确认!");
        }
        message.setTitle(title);
        if (messageInfo.length() > 255) {
            throw new BdexGatewayException("发布的内容过长，请确认!");
        }
        message.setMessage(messageInfo);
        message.setUpdateTime(cur);
        messageMapper.updateByPrimaryKeySelective(message);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void releaseMessage(Integer id) throws BdexGatewayException {
        Message message = messageMapper.selectByPrimaryKey(id);

        if (!message.getFlag().equals(Byte.valueOf("0"))) {
            throw new BdexGatewayException("该消息已发布，不能重复发布,请确认!");
        }

        Date cur = new Date();
        message.setFlag(Byte.valueOf("1"));
        message.setUpdateTime(cur);
        messageMapper.updateByPrimaryKeySelective(message);

        //为每个用户新增一条未读记录
        List<User> userIds = userService.selectAll();
        MessageUser mu = null;
        for (User u : userIds) {
            mu = new MessageUser();
            mu.setUserId(u.getId());
            mu.setMessageId(message.getId());
            mu.setFlag(Byte.valueOf("0"));
            mu.setCreateTime(cur);
            mu.setUpdateTime(cur);
            messageUserMapper.insert(mu);
        }
    }

    //获取发布消息
    @Override
    public BdexResult queryMessageList(Integer pageNumber, Integer pageSize) throws BdexGatewayException {

        //标识分页开始
        PageHelper.startPage(pageNumber, pageSize);
        List<Message> messagesList = new ArrayList<>();
        String messageRelease = redisUtil.get("MessageInfo");
        if (StringUtils.isEmpty(messageRelease)) {
            messagesList = messageMapper.queryMessageList();
        } else {
            messagesList = JSONArray.parseArray(messageRelease).toJavaList(Message.class);
        }
        //封装当前页和记录总数对象
        PageInfo<Message> pageInfo = new PageInfo<Message>(messagesList);

        return new BdexResult(pageInfo.getTotal(), pageInfo.getList());

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertUserMessage(String userId, String title, String messageInfo, String amount, String coinType,String status) throws BdexGatewayException {
        Date cur = new Date();
        //Message实体类参数的设置
        Message message = new Message();
        message.setMessageType(Byte.valueOf("1"));
        message.setFlag(Byte.valueOf("1"));
        message.setStatus(new Byte(status));
        message.setCreateTime(cur);
        message.setUpdateTime(cur);
        message.setTitle(title);
        message.setAmount(amount);
        message.setCoinType(coinType);
        message.setMessage(messageInfo);

        //插入一条消息记录
        messageMapper.insert(message);

        //为用户新增一条未读记录
        MessageUser mu = new MessageUser();
        mu.setUserId(userId);
        mu.setMessageId(message.getId());
        mu.setFlag(Byte.valueOf("0"));
        mu.setCreateTime(cur);
        mu.setUpdateTime(cur);
        messageUserMapper.insert(mu);
    }

    @Transactional(readOnly = true)
    @Override
    public Page<Message> pageData(String userId, Byte flag) {
        return messageMapper.pageData(userId, flag);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void readMessage(String userId, String messageId) {
        messageUserMapper.updateFlag(userId, messageId, Byte.valueOf("1"), new Date());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delMessage(String userId, String messageId) {
        messageUserMapper.updateFlag(userId, messageId, Byte.valueOf("2"), new Date());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void readAllMessage(String userId) {
        messageUserMapper.updateUserAllFlag(userId, Byte.valueOf("1"), new Date());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delAllMessage(String userId) {
        messageUserMapper.updateUserAllFlag(userId, Byte.valueOf("2"), new Date());
    }

    @Transactional(readOnly = true)
    @Override
    public Page<Message> pageManagerData(Map<String, Object> condition) throws BdexGatewayException {
        return messageMapper.pageManagerData(condition);
    }
}
